#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/8/13 16:31
# @USER    : Shengji He
# @File    : WordSearch.py
# @Software: PyCharm
# @Version  : Python-
# @TASK:
from typing import List


class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        """
        Given a 2D board and a word, find if the word exists in the grid.

        The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are
        those horizontally or vertically neighboring. The same letter cell may not be used more than once.

        Example:
            board =
            [
              ['A','B','C','E'],
              ['S','F','C','S'],
              ['A','D','E','E']
            ]

            Given word = "ABCCED", return true.
            Given word = "SEE", return true.
            Given word = "ABCB", return false.


        Constraints:
            - board and word consists only of lowercase and uppercase English letters.
            - 1 <= board.length <= 200
            - 1 <= board[i].length <= 200
            - 1 <= word.length <= 10^3

        :param board:
        :param word:
        :return:
        """
        self._board = board
        self._word = word
        self.rows, self.columns = len(board), len(board[0])
        for i in range(self.rows):
            for j in range(self.columns):
                if board[i][j] == word[0]:
                    if len(word) == 1:
                        return True
                    if self.__helper(1, [(i, j)]):
                        return True
        return False

    def __helper(self, pos: int, visited):
        i, j = visited[-1]
        if i > 0 and self._board[i - 1][j] == self._word[pos] and (i - 1, j) not in visited:
            if pos == len(self._word) - 1:
                return True
            visited.append((i - 1, j))
            if self.__helper(pos + 1, visited):
                return True
            else:
                visited.pop()

        if i < self.rows - 1 and self._board[i + 1][j] == self._word[pos] and (i + 1, j) not in visited:
            if pos == len(self._word) - 1:
                return True
            visited.append((i + 1, j))
            if self.__helper(pos + 1, visited):
                return True
            else:
                visited.pop()

        if j > 0 and self._board[i][j - 1] == self._word[pos] and (i, j - 1) not in visited:
            if pos == len(self._word) - 1:
                return True
            visited.append((i, j - 1))
            if self.__helper(pos + 1, visited):
                return True
            else:
                visited.pop()

        if j < self.columns - 1 and self._board[i][j + 1] == self._word[pos] and (i, j + 1) not in visited:
            if pos == len(self._word) - 1:
                return True
            visited.append((i, j + 1))
            if self.__helper(pos + 1, visited):
                return True
            else:
                visited.pop()

        return False


if __name__ == '__main__':
    S = Solution()
    board = [
        ['A', 'B', 'C', 'E'],
        ['S', 'F', 'C', 'S'],
        ['A', 'D', 'E', 'E']
    ]
    word = 'ABCB'
    # word = 'ABCCED'
    # word = 'SEE'
    print(S.exist(board, word))
    print('done')
